﻿@{
    Check.User(Can.EditFormItems);

    Page.Title = "Manage Forms";
    var formId = 0;
    var db = Database.Open((string)App.Database);
    var commandText = @"SELECT FormId, FormName FROM Forms";
    var forms = db.Query(commandText).Select(f => new SelectListItem {
        Value = f.FormId.ToString(),
        Text = f.FormName,
        Selected = f.FormId == (Request["FormId"].IsEmpty() ? UrlData[0].AsInt() : Request["FormId"].AsInt())
    });

    var formFields = Enumerable.Empty<dynamic>();

    if (UrlData[0].IsInt() || !Request["FormId"].IsEmpty()) {
        formId = Request["FormId"].IsEmpty() ? UrlData[0].AsInt() : Request["FormId"].AsInt();
        commandText = @"SELECT FormFieldId, FieldName, DataType, DisplayOrder FROM FormFields 
                        INNER JOIN FieldDataTypes ON FormFields.DataTypeId = FieldDataTypes.DataTypeId 
                        WHERE FormId = @0 ORDER BY DisplayOrder";
        formFields = db.Query(commandText, formId);
    }
}

<form method="post" class="form-horizontal">
    <fieldset>
        <legend>Manage Form</legend>
        @ControlGroup.DropDownList("Choose Form: ", "FormId", forms, " --Choose Form-- ")
    </fieldset>
</form>
<button class="btn btn-mini btn-success" type="button" id="newField">Add New Field</button>
@if (formFields.Any()) {
    foreach (var field in formFields) {
        
        <div class="widget">
            <div class="widget-actions"><a href="/Admin/Widgets/FormWidgetFields/@formId/?formFieldId=@field.FormFieldId">Edit</a> | Delete</div>
            @field.FieldName (@field.DataType)
        </div>
    }
}

@section Script {
    <script>
        $(function() {
            $('#FormId').change(function() {
                if ($(this).val() != '') {
                    $(this).closest('form').submit();
                }
            });
            $('#newField').click(function() {
                location.href = '/Admin/Widgets/FormWidgetFields/@formId';
            });
        });
    </script>
}
